<template>
  <div style="padding:0 20px 20px 20px;">
	  <a-tabs defaultActiveKey="1" @change="callback">
	    <a-tab-pane key="1" tab="操作日志">
	      <div style="margin-bottom: 16px">
	        <a-range-picker
	          @change="onDateChange"
	          style="width: 250px; margin-right: 16px"
	        />
	        <a-input-search
	          placeholder="输入用户名或IP搜索"
	          style="width: 250px; margin-right: 16px"
	          @search="onSearch"
	        />
	        <a-button type="primary" @click="exportLogs">
	          <a-icon type="download" />导出日志
	        </a-button>
	      </div>
	  
	      <a-table
	        :columns="columns"
	        :dataSource="data"
	        :pagination="pagination"
	        :loading="loading"
	        @change="handleTableChange"
	      >
	       <!-- <template slot="operation" slot-scope="text, record">
	          <a-popconfirm
	            title="确定要回滚此操作吗?"
	            @confirm="() => rollbackOperation(record)"
	            okText="确定"
	            cancelText="取消"
	          >
	            <a href="javascript:;" v-if="record.operationType !== '查询'">回滚</a>
	          </a-popconfirm>
	        </template> -->
	      </a-table>
	    </a-tab-pane>
	  
	    <a-tab-pane key="2" tab="统计报表" forceRender>
	      <div style="margin-bottom: 24px">
	        <a-radio-group defaultValue="day" buttonStyle="solid" @change="onChartTypeChange">
	          <a-radio-button value="day">日统计</a-radio-button>
	          <a-radio-button value="week">周统计</a-radio-button>
	          <a-radio-button value="month">月统计</a-radio-button>
	        </a-radio-group>
	      </div>
	  
	      <a-row :gutter="16">
	        <a-col :span="12">
	          <div style="background: #fff; padding: 16px; border-radius: 4px">
	            <h3>操作类型分布</h3>
	            <a-divider style="margin: 12px 0" />
	            <div id="operationPieChart" style="height: 300px"></div>
	          </div>
	        </a-col>
	        <a-col :span="12">
	          <div style="background: #fff; padding: 16px; border-radius: 4px">
	            <h3>操作趋势</h3>
	            <a-divider style="margin: 12px 0" />
	            <div id="operationLineChart" style="height: 300px"></div>
	          </div>
	        </a-col>
	      </a-row>
	    </a-tab-pane>
	  </a-tabs>
  </div>
</template>

<script>
import { querySysLogPageList } from '@/api/common/api'
import moment from 'moment'

export default {
  name: 'LogManagement',
  data() {
    return {
      columns: [
        {
          title: '序号',
          dataIndex: 'id',
          width: '5%',
          customRender: (text, record, index) => {
            return (this.pagination.current - 1) * this.pagination.pageSize + index + 1
          }
        },
        {
          title: '日志类型',
          dataIndex: 'logType',
          width: '8%',
          customRender: (text) => this.getLogTypeText(text)
        },
        {
          title: '操作用户',
          dataIndex: 'userid',
          width: '8%'
        },
        {
          title: '操作类型',
          dataIndex: 'operateType',
          width: '8%',
          customRender: (text) => this.getOperateTypeText(text)
        },
        {
          title: '日志内容',
          dataIndex: 'logContent',
          width: '25%',
          ellipsis: true
        },
        {
          title: 'IP地址',
          dataIndex: 'ip',
          width: '10%'
        },
        {
          title: '请求方法',
          dataIndex: 'method',
          width: '15%',
          ellipsis: true
        },
        {
          title: '耗时(ms)',
          dataIndex: 'costTime',
          width: '8%',
          align: 'right',
          customRender: (text) => text || '--'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          width: '15%',
          customRender: (text) => this.formatTime(text)
        }
      ],
      data: [],
      pagination: {
        current: 1,
        pageSize: 10,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: total => `共 ${total} 条记录`,
        total: 0
      },
      loading: false,
      queryParam: {
        beginDate: '',
        endDate: '',
        userid: '',
        pageNo: 1,
        pageSize: 10
      }
    };
  },
  created() {
    this.loadData();
    this.renderCharts();
  },
  methods: {
    callback(key) {
      console.log(key);
      if (key === '2') {
        this.$nextTick(() => {
          this.renderCharts();
        });
      }
    },
    onDateChange(dates, dateStrings) {
      this.queryParam.beginDate = dateStrings[0];
      this.queryParam.endDate = dateStrings[1];
      this.loadData();
    },
    onSearch(value) {
      this.queryParam.userid = value;
      this.loadData();
    },
    exportLogs() {
      this.$message.info('导出功能开发中');
    },
    rollbackOperation(record) {
      console.log('回滚操作:', record);
      this.$message.success(`正在回滚ID为 ${record.id} 的操作`);
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.loadData()
    },
    onChartTypeChange(e) {
      console.log('图表类型:', e.target.value);
      this.renderCharts();
    },
    renderCharts() {
      // 模拟图表数据
      const operationCounts = {
        '查询': 0,
        '新增': 0,
        '修改': 0,
        '删除': 0
      };
      
      this.data.forEach(item => {
        operationCounts[item.operationType]++;
      });
      
      // 模拟渲染饼图
      const pieChart = document.getElementById('operationPieChart');
      if (pieChart) {
        // 实际应用中会使用 ECharts 等库
        pieChart.innerHTML = `
          <div style="text-align: center; padding-top: 100px">
            <div style="display: inline-block; text-align: left">
              <div><span style="display: inline-block; width: 12px; height: 12px; background: #1890ff; margin-right: 8px;"></span>查询: ${operationCounts['查询']}</div>
              <div><span style="display: inline-block; width: 12px; height: 12px; background: #52c41a; margin-right: 8px;"></span>新增: ${operationCounts['新增']}</div>
              <div><span style="display: inline-block; width: 12px; height: 12px; background: #faad14; margin-right: 8px;"></span>修改: ${operationCounts['修改']}</div>
              <div><span style="display: inline-block; width: 12px; height: 12px; background: #f5222d; margin-right: 8px;"></span>删除: ${operationCounts['删除']}</div>
            </div>
          </div>
        `;
      }
      
      // 模拟渲染折线图
      const lineChart = document.getElementById('operationLineChart');
      if (lineChart) {
        // 模拟7天数据
        const days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
        const lineData = days.map(day => Math.floor(Math.random() * 20) + 5);
        
        lineChart.innerHTML = `
          <div style="text-align: center; padding-top: 50px">
            <div style="display: inline-block; width: 80%; height: 200px; border-left: 1px solid #ddd; border-bottom: 1px solid #ddd; position: relative;">
              ${lineData.map((count, index) => `
                <div style="position: absolute; bottom: 0; left: ${(index * 14.28) + 7}%; width: 10%; height: ${(count / Math.max(...lineData)) * 100}%; background: #1890ff;">
                  <div style="position: absolute; top: -20px; left: 0; right: 0; text-align: center; font-size: 12px;">${count}</div>
                </div>
                <div style="position: absolute; bottom: -25px; left: ${(index * 14.28) + 7}%; width: 10%; text-align: center; font-size: 12px;">${days[index]}</div>
              `).join('')}
            </div>
          </div>
        `;
      }
    },
    logout() {
      this.$message.success('退出登录成功');
      // 实际应用中会有路由跳转逻辑
    },
    loadData() {
      this.loading = true
      const params = {
        ...this.queryParam,
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize
      }
      
      querySysLogPageList(params).then(res => {
        if (res.success) {
          this.data = res.result.list || []
          this.pagination.total = res.result.totalRecord
        } else {
          this.$message.error(res.message || '获取日志列表失败')
        }
      }).catch(err => {
        console.error('获取日志列表失败:', err)
        this.$message.error('获取日志列表失败')
      }).finally(() => {
        this.loading = false
      })
    },
    formatTime(text) {
      return text || '--';
    },
    getOperateTypeText(type) {
      const typeMap = {
        1: '添加',
        2: '更新',
        3: '删除',
        4: '状态'
      };
      return typeMap[type] || '--';
    },
    getLogTypeText(type) {
      const typeMap = {
        1: '登录日志',
        2: '操作日志',
        3: '查询日志'
      };
      return typeMap[type] || '--';
    }
  },
};
</script>

<style>
#components-layout-demo-top-side-2 .logo {
  width: 120px;
  height: 31px;
  background: rgba(255, 255, 255, 0.2);
  margin: 16px 28px 16px 0;
  float: left;
}
</style>